/*
 * Copyright 2013 Clareity Security, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.clareitysecurity.shibboleth.storage;

import java.util.ArrayList;

import net.clareitysecurity.shibboleth.db.SessionObjectDAOImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.clareity.shibboleth.db.CsIdpSession;

public class StorageCleaner<KeyType> implements Runnable {

	private final Logger log = LoggerFactory.getLogger(StorageCleaner.class);
	public final static String version = "Version 1.0.1 (2013-08-27)";
	
	private String systemName;
	private boolean work = true;
	private DbStorageService<KeyType, ?> storageService = null;
	
	
	@Override
	public void run() {
		log.info(version);
		
		if (storageService == null) {
			log.error("Storage service is null. Exiting.");
			return;
		}
		
		try {
			int count = 0;
			log.info("Searching for orphaned and expired sessions for system [{}]", systemName);
			ArrayList<CsIdpSession> sessionList = (ArrayList<CsIdpSession>) SessionObjectDAOImpl.getExpiredSessions(systemName);
			
			for (CsIdpSession session: sessionList) {
				storageService.remove(DbStorageService.sessionPartition, (KeyType)session.getSessionId());
				count++;
				
				if (work == false) {
					log.info("Exiting storage cleaner before work is done.");
					return;
				}
			}
			
			log.info("Storage cleaner exiting after removing orphaned sessions. [{}]", count);
		} catch (Exception e) {
			log.error("", e);
			return;
		}
	}

	public String getSystemName() {
		return systemName;
	}

	public void setSystemName(String systemName) {
		this.systemName = systemName;
	}

	public boolean isWork() {
		return work;
	}

	public void setWork(boolean work) {
		this.work = work;
	}

	public DbStorageService<KeyType, ?> getStorageService() {
		return storageService;
	}

	public void setStorageService(DbStorageService<KeyType, ?> storageService) {
		this.storageService = storageService;
	}

}
